<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Curl;
use App\Http\Controllers\ErrorCode;
use App\Http\Controllers\SuccessCode;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Common;
use App\Model\Order as OrderModel;
use Schema;
use Validator;


class Order extends Controller
{
    use Common;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $startTime = $request->get('start_time','');
        $endTime   = $request->get('end_time','');
        $orderNo   = $request->get('order_number','');
        $orderType = $request->get('order_type',0);
        $uid       = $request->get('uid','');
        $status    = $request->get('status');
        $payType   = $request->get('pay_type','');

        $params = [];

        if ($startTime){
            $params['create_time']['key'] = 'create_time';
            $params['create_time']['condition'] = '>=';
            $params['create_time']['value'] = strtotime($startTime);
        }

        if ($endTime){
            $params['create_time']['key'] = 'create_time';
            $params['create_time']['condition'] = '<=';
            $params['create_time']['value'] = strtotime($endTime) + 86400;
        }

        if ($orderNo){
            $params['order_number']['key'] = 'order_number';
            $params['order_number']['condition'] = '=';
            $params['order_number']['value'] = $orderNo;
        }

        if ($uid){
            $params['uid']['key'] = 'uid';
            $params['uid']['condition'] = 'in';
            $params['uid']['value'] = explode(',',$uid);
        }

        if ($status == '0' || $status){
            $params['status']['key'] = 'status';
            $params['status']['condition'] = '=';
            $params['status']['value'] = $status;
        }

        if ($payType){
            $params['pay_type']['key'] = 'pay_type';
            $params['pay_type']['condition'] = '=';
            $params['pay_type']['value'] = $payType;
        }

        $pageSize = $request->get('paginate',config('web.page.num'));

        if (!empty($params)){
            $lists = new OrderModel();
            foreach ($params as $param) {
                if ($param['condition'] == 'in'){
                    $lists = $lists->whereIn($param['key'],$param['value']);
                } else {
                    $lists = $lists->where($param['key'],$param['condition'],$param['value']);
                }
            }

            $lists = $lists->where('order_type',$orderType)
                ->orderBy('create_time','DESC')
                ->paginate($pageSize);

        } else {
            $lists = OrderModel::where('order_type',$orderType)
                ->orderBy('create_time','DESC')
                ->paginate($pageSize);
        }

        foreach ($lists as $key => $list) {
            $lists[$key]->status = config('web.order')[$list->status];
            $lists[$key]->create_time = date('Y-m-d H:i:s',$lists[$key]->create_time);
        }

        return $this->getView($lists,SuccessCode::GET_SUCCESS);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();

        \Log::info('======下单请求参数开始========');

        \Log::info('',$data);

        \Log::info('======下单请求参数结束========');

        $rule = [
            'uid'         => 'bail|required',
            'game_id'     => 'bail|required',
            //'prop_name'   => 'bail|required',
            //'prop_num'    => 'bail|required',
            'total_money' => 'bail|required|numeric',
            'pay_type'    => 'bail|required',
            'channel_id' => 'bail|required'
        ];

        $fields = [
            'uid','game_id',
            'total_money','pay_type','channel_id',
            'money','platform_currency'
        ];

        //支付类型 1：支付宝   2：微信，3：银联 ，4：平台币，5，宝币
        $pay = ['alipay','weixin','unionpay'];


        $payTypes = explode(',',$request->get('pay_type')) ;

        if (is_array($payTypes)){
            foreach ($payTypes as $payType) {
                if (isset(config('web.pay')[$payType])){
                    if (in_array($payType, $pay) ){
                        $rule['money'] = 'bail|required|numeric';
                    } elseif ($payType == 'platform'){
                       $rule['platform_currency'] = 'bail|required|numeric';
                    }
                }else {
                    return $this->getView([],sprintf(ErrorCode::PARAMS_ERROR,'pay type 参数错误'));
                }
            }
        }

        $validator = Validator::make($request->all(),$rule);
        if ($validator->fails()){
            $messages = $validator->errors();
            foreach ($fields as $field) {
                if ($messages->has($field)) {
                    return $this->getView([],sprintf(ErrorCode::PARAMS_ERROR,$messages->first($field)));
                }
            }
        }

        if (isset($data['order_type']) && $data['order_type'] == 1){
            $orderSn = 'PTB' . date('Ymd') . rand(1000, 9999);
        } else {
            $yCode = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L'];
            $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));

            $params = [
                'url' => config('web.api.public_url') . 'gameStatus',
                'isPost' => false,  //post方式
                'dataStr' => [ //参数
                    'game_id' => $request->input('game_id'),
                    'chairman_id' => $request->input('channel_id'),
                    'query_type' => 'pay_status',
                ]
            ];
            $str = Curl::query($params);
            $res = json_decode($str,true);
            if (!$res){
                return $this->getView([$str],ErrorCode::SYSTEM_ERROR);
            }

            if ($res['code'] != '0'){
                return $res;
            }
        }

        $totalMoney = $data['total_money'];
        $money = 0;
        $platform_currency = 0;
        //支付类型 1：支付宝   2：微信，3：银联 ，4：平台币，5，宝币
        $type = $request->get('pay_type');

        //1：支付宝   2：微信，3：银联
        if ($type == 'alipay' || $type == 'weixin' || $type=='unionpay'){
            $money = $data['money'];
            $platform_currency  = 0;
            $data['platform_currency'] = 0;
        }

        //4：平台币，
        if ($type == 'platform'){
            $data['money'] = $money;
            $platform_currency  = $data['platform_currency'];
        }

        //支付宝 + 平台币 || 微信 + 平台币
        if ($type == 'alipay,platform' || $type == 'weixin,platform'){
            $money = $data['money'];
            $platform_currency = $data['platform_currency'];
        }

        if (($platform_currency+$money) != $totalMoney){
            return $this->getView([],sprintf(ErrorCode::PARAMS_ERROR,'请核对金额数'));
        }

        $data['order_number'] = $orderSn;
        $data['create_time'] = time();
        $data['pay_money'] = $data['total_money'];
        $data['status'] = 1;

        //状态  0：已完成,1等待支付，2，取消订单，3，订单超时，4，支付成功，5支付失败。

        $fields = Schema::getColumnListing('orders');

        foreach ($data as $field => $value) {
            if (!in_array($field,$fields)){
                unset($data[$field]);
            }
        }

        if (OrderModel::insert($data)){
            unset($data['status']);
            $data['notify_url'] = config('web.payment.alipay');
            return $this->getView($data,SuccessCode::ADD_SUCCESS);
        } else {
            return $this->getView([],ErrorCode::ADD_ERROR);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 更改订单支付方式
     *
     * @param  int  $orderNo
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $orderNo)
    {
        $type = $request->get('payType','');

        $oldType = OrderModel::where('order_number',$orderNo)->first();

        if ($oldType && $oldType->pay_type != $type){
            OrderModel::where('order_number',$orderNo)->update([
                'pay_type' => $type
            ]);
        }

        return $this->getView([],SuccessCode::EDIT_SUCCESS);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    //获取会长平台币充值记录
    public function getOrderByChairman(Request $request,$userId)
    {
        $startTime = $request->get('start_time','');
        $endTime   = $request->get('end_time','');
        $orderNo   = $request->get('order_number','');
        $status    = $request->get('status','');

        $params = [];

        if ($startTime){
            $params['create_time']['key'] = 'create_time';
            $params['create_time']['condition'] = '>=';
            $params['create_time']['value'] = strtotime($startTime);
        }

        if ($endTime){
            $params['create_time']['key'] = 'create_time';
            $params['create_time']['condition'] = '<=';
            $params['create_time']['value'] = strtotime($endTime) + 86400;
        }

        if ($orderNo){
            $params['order_number']['key'] = 'order_number';
            $params['order_number']['condition'] = '=';
            $params['order_number']['value'] = $orderNo;
        }

        if ($status){
            $params['status']['key'] = 'status';
            $params['status']['condition'] = '=';
            $params['status']['value'] = $status;
        }

        $pageSize = $request->get('paginate',config('web.page.num'));

        if (!empty($params)){
            $model = new OrderModel();
            foreach ($params as $param) {
                $lists = $param['condition'] == 'in' ?
                    $model->whereIn($param['key'],$param['value']) :
                    $model->where($param['key'],$param['condition'],$param['value']);
            }
            $lists = $lists->where('order_type',1)
                ->where('uid',$userId)
                ->orderBy('create_time','DESC')
                ->paginate($pageSize);
        } else {
            $lists = OrderModel::where('uid',$userId)
                ->where('order_type',1)
                ->orderBy('create_time','DESC')
                ->paginate($pageSize);
        }

        foreach ($lists as $key => $list) {
            $lists[$key]->status = config('web.order')[$list->status];
            $lists[$key]->create_time = date('Y-m-d H:i:s',$lists[$key]->create_time);
        }

        return $this->getView($lists,SuccessCode::GET_SUCCESS);
    }

    //更改订单状态
    public function changeOrderStatus(Request $request)
    {
        $data = $request->all();
        $res = OrderModel::verify($data,1);
        if (!$res){
            return $this->getView([],OrderModel::$error);
        } else {
            return $this->getView($res,SuccessCode::EDIT_SUCCESS);
        }
    }
}
